﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DotNetCore.BannerManagement.Domain;
using System.Data.SqlClient;
using System.Diagnostics;
using Microsoft.Practices.Repository;
using Microsoft.Practices.Repository.SQLServer;

namespace DotNetCore.BannerManagement.DAL.Domain.dnc_ImpressionRepositoryArtifacts
{
    /// <summary>
    /// Respository that lets you find dnc_Impression in the
    /// CRM database.
    /// </summary>
    public class dnc_ImpressionRepository : Repository<dnc_Impression>, Idnc_ImpressionRepository
    {
        public dnc_ImpressionRepository(string databaseName)
            : base(databaseName)
        {
        }

        public dnc_ImpressionRepository()
            : base()
        {
        }


        public List<dnc_Impression> GetAllFromdnc_Impression()
        {
            ISelectionFactory<NullableIdentity> selectionFactory = new GetAllFromdnc_ImpressionSelectionFactory();

            try
            {
                NullableIdentity nullableIdentity = new NullableIdentity();
                return base.Find(selectionFactory, new GetAllFromdnc_ImpressionFactory(), nullableIdentity);
            }
            catch (SqlException ex)
            {
                HandleSqlException(ex, selectionFactory);
            }

            return new List<dnc_Impression>();
        }

        public void Add(dnc_Impression dnc_Impression)
        {
            dnc_ImpressionInsertFactory insertFactory = new dnc_ImpressionInsertFactory();
            try
            {
                base.Add(insertFactory, dnc_Impression);
            }
            catch (SqlException ex)
            {
                HandleSqlException(ex, insertFactory);
            }
        }

        private void HandleSqlException(SqlException ex, IDbToBusinessEntityNameMapper mapper)
        {
            if (ex.Number == ErrorCodes.SqlUserRaisedError)
            {
                switch (ex.State)
                {
                    case ErrorCodes.ValidationError:
                        string[] messageParts = ex.Errors[0].Message.Split(':');
                        throw new RepositoryValidationException(
                            mapper.MapDbParameterToBusinessEntityProperty(messageParts[0]),
                            messageParts[1], ex);

                    case ErrorCodes.ConcurrencyViolationError:
                        throw new ConcurrencyViolationException(ex.Message, ex);

                }
            }

            throw new RepositoryFailureException(ex);
        }
    }
}

